package com.design.module.utils;

import javax.servlet.http.HttpServletRequest;

import com.design.framework.cache.CachePool;
import com.design.framework.cache.service.RedisServiceImpl;
import com.design.framework.utils.SerializeUtil;
import com.design.framework.utils.SpringContextHolder;
import com.design.framework.utils.StringUtils;
import com.design.module.dao.UserDao;
import com.design.module.entity.User;

/**
 * 用户工具类
 * 
 * @author JohnDeng
 * @datatime 2018年5月2日下午5:24:53
 */
public class UserUtils {

	public static String getToken(HttpServletRequest request) {
		return request.getHeader("Token");
	}

	/**
	 * 获取用户信息,首先去redis查找，如果没有就去数据库查找
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author John
	 * @datatime 2017年12月7日下午4:22:26
	 */
	public static User getUser(HttpServletRequest request) {
		User user = null;
		String id = getUserId(request);
		try {
			RedisServiceImpl redisServiceImpl = SpringContextHolder.getBean(RedisServiceImpl.class);
			if (redisServiceImpl.exists(id.getBytes())) {
				byte[] byt = redisServiceImpl.get(id.getBytes());
				user = SerializeUtil.deserialize(byt, User.class);
				return user;
			} else {
				UserDao userDao = SpringContextHolder.getBean(UserDao.class);
				user = new User();
				user.setId(id);
				user = userDao.get(user);
				if (user != null) {
					redisServiceImpl.set(SerializeUtil.serialize(id), SerializeUtil.serialize(user), 1800);
					return user;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过token获取用户id
	 * 
	 * @author JohnDeng 2017年11月14日上午11:53:54
	 * @param
	 * @return
	 * @throws Exception
	 */
	public static String getUserId(HttpServletRequest request) {
		String token = getToken(request);
		if (StringUtils.isEmpty(token)) {
			return "";
		}
		try {
			RedisServiceImpl redisServiceImpl = SpringContextHolder.getBean(RedisServiceImpl.class);
			if (redisServiceImpl != null) {
				if (redisServiceImpl.exists(token)) {
					return (String) redisServiceImpl.get(token);
				} else if (CachePool.getInstance().containKey(token)) {
					return (String) CachePool.getInstance().getCacheItem(token);
				}
			} else if (CachePool.getInstance().containKey(token)) {
				return (String) CachePool.getInstance().getCacheItem(token);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
